import re

from django import http
from django.contrib.auth import  authenticate,login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from pymysql import DatabaseError

from apps.users.models import User


class UserView(LoginRequiredMixin,View):
    '''个人中心'''

    def get(self,request):

        context={
            'username':request.user.username
        }

        return render(request,'user.html',context)

class GerenView(LoginRequiredMixin,View):
    '''个人信息'''

    def get(self,request):
        context={
            'username':request.user.username
        }

        return render(request,'xinxi.html',context)

class NamechangeView(LoginRequiredMixin,View):
    '''修改名字'''
    def get(self,request):

        return render(request,'namechange.html')

    def post(self,request):

        user_id=request.user.id
        try:
            User.objects.get(id=user_id)
        except Exception as e:
            return http.HttpResponseBadRequest('不是当前用户')
        # 获取参数
        username=request.POST.get('username')

        if not all([username]):
            return http.HttpResponseBadRequest('缺少参数')

        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')

        try:
            user=User.objects.get(id=request.user.id)
            user.username=username
            user.save()
        except Exception as e:
            return http.HttpResponseBadRequest('名字不正确')

        return redirect(reverse('users:users'))

class LoginView(View):
    '''登录页面'''
    def get(self,request):

        return render(request,'login.html')

    def post(self,request):
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        # remembered = request.POST.get('remembered')
        print(username,password)
        # 校验参数
        # 判断参数是否齐全
        if not all([username, password]):
            return http.HttpResponseBadRequest('缺少必传参数')

        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{3,20}$', username):
            # return http.HttpResponseBadRequest('请输入正确的用户名或手机号')
            return render(request, 'login.html', {'account_errmsg': '请输入正确的用户名或手机号'})

        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{3,20}$', password):
            # return http.HttpResponseBadRequest('密码最少8位，最长20位')
            return render(request, 'login.html', {'account_errmsg': '密码最少8位，最长20位'})
        print(1111111111111)
        # 认证登录用户
        user=request.user = authenticate(username=username, password=password)
        print(222222222)
        # if user is  None:
        #     print(333333333)
        #     return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        print(44444)
        # 实现状态保持
        login(request, user)
        print(555555)
        # 设置状态保持的周期
        # if remembered != 'on':
        #     # 没有记住用户：浏览器会话结束就过期
        #     request.session.set_expiry(0)
        # else:
        #     # 记住用户：None表示两周后过期
        #     request.session.set_expiry(None)

        # 响应登录结果
        # return redirect(reverse('index:index'))
        # 响应注册结果
        response = redirect(reverse('users:users'))
        # # 响应登录结果
        # next = request.GET.get('next')
        # if next:
        #     response = redirect(next)
        # else:
        #     response = redirect(reverse('index:index'))
        print(33333333333333)
        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 合并购物车
        # response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response



class RegisterView(View):
    '''注册页面'''
    def get(self,request):

        return render(request,'register.html')


    def post(self,request):
        '''注册'''
        # 1. 获取参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        # mobile = request.POST.get('mobile')
        # allow = request.POST.get('allow')
        # sms_code = request.POST.get('sms_code')

        # 2. 校验参数
        # 判断参数是否齐全
        if not all([username, password, password2, ]):
            return http.HttpResponseBadRequest('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{6,20}$', password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')
        # # 判断手机号是否合法
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseBadRequest('请输入正确的手机号码')
        # 判断是否勾选用户协议
        # if allow != 'on':
        #     return http.HttpResponseBadRequest('请勾选用户协议')

        # redis_conn = get_redis_connection('code')
        # sms_code_saved = redis_conn.get('sms_%s' % mobile)
        # if sms_code_saved is None:
        #     return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        # if sms_code != sms_code_saved.decode():
        #     return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 3. 创建用户
        # 保存注册数据
        try:
            user = User.objects.create_user(username=username, password=password)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 4. 响应注册结果
        # return redirect(reverse('index:index'))
        response = redirect(reverse('users:login'))

        # 注册时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)

        # 退出登录，重定向到登录页
        response = redirect(reverse('index:index'))

        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class XiugaiView(LoginRequiredMixin,View):
    '''修改密码'''
    def get(self,request):

        return render(request,'password.html')

    def post(self,request):
        # 1.接收参数
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        # 2.验证参数

        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[0-9A-Za-z]{3,20}$', new_password):
            return http.HttpResponseBadRequest('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')

        # 3.检验旧密码是否正确
        if not request.user.check_password(old_password):
            return render(request, 'password.html', {'origin_password_errmsg': '原始密码错误'})

        # 4.更新新密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return render(request, 'password.html', {'change_password_errmsg': '修改密码失败'})
        # 5.退出登陆,删除登陆信息

        logout(request)
        # 6.跳转到登陆页面
        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response

